<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 *
 * @author 安鹏飞
 * @date 2017-10-12
 */
class Count extends MY_Controller
{
	public function __construct() {
	        parent::__construct();
	        $this->load->model('M_device');
	}
	/*
		设备报修情况统计表
	 */
	public function device_report()
	{

		$start_time = $this->input->post('start_time');
		$end_time = $this->input->post('end_time');
		$start_time = strtotime($start_time);
		$end_time = strtotime($end_time);
		$list = $this->db->select('device_type_name,t_device.device_name,grid_name,report_addtime,report_file,report_voice,report_remark,report_user_name,department_name,report_status')
				->from('t_device_report')
				->join('t_device','t_device.device_id = t_device_report.device_id','left')
				->join('t_device_type','t_device_type.device_type_id = t_device.device_type_id','left')
				->join('t_department','t_department.department_id = t_device_type.department_id','left')
				->join('t_grid','t_grid.grid_id = t_device.grid_id','left')
				->where('report_addtime >=',$start_time)
				->or_where('report_addtime <=',$end_time)
				->get()
				->result_array();
		if($list)
		{
			foreach($list as $k => $v)
			{
				$list[$k]['report_addtime'] = date("Y-m-d H:i:s",$v['report_addtime']);
			}
			$res['code'] = 0;
			$res['info'] = "获取设备报修情况成功";
			$res['data'] = $list;
		}else{
			$res['code'] = 1;
			$res['info'] = "获取设备报修情况失败";
		}

		echo json_encode($res);

	}
	//设备报修记录表
	public function record(){
	             $page       = getParam($this->input->get_post("page"),'int',1);
	             $status = $this->input->get_post("status");//状态
	             $dept = $this->input->get_post("dept");//部门
	             $starttime = $this->input->get_post("start_time");//ajax
	             $endtime = $this->input->get_post("end_time");//ajax
	             $start_time = strtotime($starttime);
	             $end_time = strtotime(date('Y-m-d 23:59:59', strtotime($endtime)));
	             $where=' where r.report_addtime>='.$start_time.' AND r.report_addtime<='.$end_time;
	             if(!empty($status)){
	             	$where.=" AND r.report_status=".$status;
	             }
	             if(!empty($dept)){
	             	$where.=" AND t.department_id=".$dept;
	             }
	             $per_page   = 10;//每一页显示的数量
	             $this->load->library("common_page");
	             $total = $this->M_device->get_Areacount($where);
	             $page_string = $this->common_page->page_string($total, $per_page, $page);
	             $limit   = ($page-1)*$per_page;
	             $limit  .=",{$per_page}";
	             $list   = $this->M_device->get_Areadata($where,$limit,$type=1);
	             $status = array('1'=>'报修','2'=>'维修','3'=>'验收','4'=>'正常');
	             if(!empty($list)){
	                        foreach($list as &$v){
	                            	$v['device_name'] = isset($v['device_name'])?$v['device_name']:""; //设备名称
	                            	$v['device_type_name'] = isset($v['device_type_name'])?$v['device_type_name']:""; //设备类型名称
	                            	$v['area_name'] = isset($v['area_name'])?$v['area_name']:"";  //设备位置
	                            	$v['grid_name'] = isset($v['grid_name'])?$v['grid_name']:"";  //网格名称
	                            	$v['department_name'] = isset($v['department_name'])?$v['department_name']:"";  //所属部门
	                            	$v['report_addtime'] = isset($v['report_addtime'])?date('Y-m-d H:i:s',$v['report_addtime']):"";  //上报时间
	                            	$v['report_status'] = $status[$v['report_status']];  //设备状态
	                            	$v['num'] = isset($v['num'])?$v['num']:"";  //维修次数
	                        	  	$v['ys'] = $this->get_time1($v['task_time'],$v['task_donetime'],$a=1);//用时
	                          }
	             }
	            exit(json_encode(array('code'=>0,'data'=>$list,'result_page'=>$page_string,'total'=>$total,'info'=>'成功')));
	}
	//故障上报详情
	public function ajax_details(){
			$reportid = $this->input->get_post("reportid", true);//上报ID
			if(empty($reportid)){
			       exit(json_encode(array('code'=>1,'info'=>'设备维护reportid不能为空！')));
			}
			$sql = "select report_user_name,report_addtime from t_device_report where report_id={$reportid}";
			$list1 = $this->db->query($sql)->row_array(); //上报人 上报时间
			//维修时间  维修人  维修截止时间   维修结果
			$sql1 = "SELECT u.user_name as username,t.task_result as result,t.task_time as tasktime,t.task_donetime as taskdonetime,t.the_task_type as type  FROM t_device_repairtask k LEFT JOIN t_device_report r ON r.report_id=k.report_id LEFT JOIN t_device_task t ON t.repairtask_id=k.repairtask_id LEFT JOIN t_user u ON u.user_id=t.user_id WHERE r.report_id={$reportid} AND the_task_type=2 AND t.task_status=1 ORDER BY t.task_addtime ASC";
			$list2 = $this->M_device->querylist($sql1);
			$sql2 = "SELECT u.user_name as username,t.task_result as result,t.task_time as tasktime,t.task_donetime as taskdonetime ,t.the_task_type as type  FROM t_device_inspecttask i LEFT JOIN t_device_report r ON r.report_id=i.report_id LEFT JOIN t_device_task t ON t.inspecttask_id=i.inspecttask_id LEFT JOIN t_user u ON u.user_id=t.user_id WHERE r.report_id={$reportid} AND the_task_type=1 AND t.task_status=1 ORDER BY t.task_addtime ASC";
			$list3 = $this->M_device->querylist($sql2);
			if(!empty($list1)){
			$list = array(
					array(
	                                                    'username'=>$list1['report_user_name'],
	                                                    'addtime'=>date('Y-m-d H:i:s',$list1['report_addtime']),
	                                                    ),

				);
			}
			$data = array();
			if(!empty($list2)){
				foreach ($list2 as $key => $value) {
					$value['tasktime'] = date('Y-m-d H:i:s',$value['tasktime']);
					$value['taskdonetime'] = date('Y-m-d H:i:s',$value['taskdonetime']);
					array_push($data, $value);
				}
			}
			if(!empty($list3)){
				foreach ($list3 as $key => $value) {
					$value['tasktime'] = date('Y-m-d H:i:s',$value['tasktime']);
					$value['taskdonetime'] = date('Y-m-d H:i:s',$value['taskdonetime']);
					array_push($data, $value);
				}
			}
			$sort_key='tasktime';
				if(!empty($data)){
					foreach ($data as $row_array)
					{
						$key =  $row_array[$sort_key];
						$key_array[] = $key;
					}  
					array_multisort($key_array,SORT_ASC,$data);
				}

		$res=array();
		$res['devinfo']=$list;
		$res['taskinfo']=$data;
                     	exit(json_encode(array('code'=>0,'data'=>$res,'info'=>'成功')));
    }

	/*
		信息上报统计表
	 */
	public function information_report()
	{

		$start_time = $this->input->post('start_time');
		$end_time = $this->input->post('end_time');
		$start_time = strtotime($start_time);
		$end_time = strtotime($end_time);
		$list = $this->db->select('t_information_type.p_id,information_type_name,information_title,grid_name,information_addtime,information_content,user_name,department_name')
				->from('t_information')
				->join('t_information_type','t_information_type.information_type_id = t_information.information_type_id','left')
				->join('t_grid','t_grid.grid_id = t_information.grid_id','left')
				->join('t_user','t_user.user_id = t_information.user_id','left')
				->join('t_department','t_department.department_id = t_user.department_id','left')
				->where('information_addtime >=',$start_time)
				->or_where('information_addtime <=',$end_time)
				->get()
				->result_array();
		if($list)
		{
			foreach($list as $k => $v)
			{
				$list2 = $this->db->select('information_type_name')
						->from('t_information_type')
						->where('information_type_id',$v['p_id'])
						->get()
						->row_array();
				unset($list[$k]['p_id']);
				$list[$k]['first_information_type_name'] = $list2['information_type_name'];
				$list[$k]['information_addtime'] = date("Y-m-d H:i:s",$v['information_addtime']);
			}
			$res['code'] = 0;
			$res['info'] = "获取设备报修情况成功";
			$res['data'] = $list;
		}else{
			$res['code'] = 1;
			$res['info'] = "获取设备报修情况失败";
		}

		echo json_encode($res);

	}

	/*
		根据年、季、月判断时间区间
	 */
	public function check_time($data)
	{

		if($data['type'] == 1)
		{
			$year = $data['year'];
			$time['first'] = $year."-01-01 00:00:00";
			$time['last'] = ($year+1)."-01-01 00:00:00";
		}else if($data['type'] == 2){
			$year = $data['year'];
			$quarter = $data['quarter'];
			if($quarter == 1)
			{
				$time['first'] = $year."-01-01 00:00:00";
				$time['last'] = $year."-04-01 00:00:00";
			}else if($quarter == 2)
			{
				$time['first'] = $year."-04-01 00:00:00";
				$time['last'] = $year."-07-01 00:00:00";
			}else if($quarter == 3)
			{
				$time['first'] = $year."-07-01 00:00:00";
				$time['last'] = $year."-10-01 00:00:00";
			}else{
				$time['first'] = $year."-10-01 00:00:00";
				$time['last'] = ($year+1)."-01-01 00:00:00";
			}
		}else{
			$year = $data['year'];
			$month = $data['month'];
			if(!is_array($month))
			{
				if($month == 12)
				{
					$time['first'] = $year."-".$month."-01 00:00:00";
					$time['last'] = ($year+1)."-01-01 00:00:00";
				}else{
					$time['first'] = $year."-".$month."-01 00:00:00";
					$time['last'] = $year."-".($month+1)."-01 00:00:00";
				}
			}else{
				foreach($month as $k => $v)
				{
					if($v == 12)
					{
						$time[$k]['first'] = $year."-".$v."-01 00:00:00";
						$time[$k]['last'] = ($year+1)."-01-01 00:00:00";
					}else{
						$time[$k]['first'] = $year."-".$v."-01 00:00:00";
						$time[$k]['last'] = $year."-".($v+1)."-01 00:00:00";
					}
				}
			}
		}

		return $time;

	}

	/*
		各网格内设备故障统计图
	 */
	public function device_trouble_chart()
	{

		$data = $this->input->post();
		unset($data['grid_id']);
		if(!empty($data['type']))
		{
			$time = $this->check_time($data);
		}else{
			$time['first'] = date('Y-m-01 00:00:00');
			$time['last'] = date('Y-m-01 00:00:00',strtotime('+1 month'));
		}
		$time['first'] = strtotime($time['first']); 
		$time['last'] = strtotime($time['last']);
		$grids = $this->input->post('grids');
		$list = $this->db->select('grid_name,count(t_device.grid_id) as device_num')
				->from('t_grid')
				->join('t_device','t_device.grid_id = t_grid.grid_id','left')
				->where_in('t_grid.grid_id',$grids)
				->group_by('t_grid.grid_id')
				->get()
				->result_array();
		$list2 = $this->db->select('grid_name,count(t_device_report.device_id) as device_trouble_num')
				->from('t_grid')
				->join('t_device','t_device.grid_id = t_grid.grid_id','left')
				->join('t_device_report','t_device_report.device_id = t_device.device_id','left')
				->where('report_addtime between '.$time['first'].' and '.$time['last'])
				->group_by('t_grid.grid_id')
				->get()
				->result_array();
		foreach($list as $k => $v)
		{
			$list[$k]['device_trouble_num'] = 0;
			foreach($list2 as $kk => $vv)
			{
				if($v['grid_name'] == $vv['grid_name'])
				{
					$list[$k]['device_trouble_num'] = $vv['device_trouble_num'];
				}
			}
		}
		if($list)
		{
			foreach($list as $k => $v)
			{
				$result['chartxname'][] = $list[$k]['grid_name'];
				$result['chartxdata'][0][] = $list[$k]['device_num'];
				$result['chartxdata'][1][] = $list[$k]['device_trouble_num'];
			}
			$res['code'] = 0;
			$res['info'] = "获取成功";
			$res['data'] = $result;
		}else{
			$res['code'] = 1;
			$res['info'] = "获取失败,暂无数据";
		}

		echo json_encode($res);

	}

	/*
		设备责任部门列表
	 */
	public function department_list()
	{

		$list = $this->db->select('t_device_type.department_id as id,department_name as text')
				->from('t_device_type')
				->join('t_department','t_department.department_id = t_device_type.department_id','left')
				->group_by('t_device_type.department_id')
				->get()
				->result_array();
		if($list)
		{
			$res['code'] = 0;
			$res['info'] = "获取责任部门列表成功";
			$res['data'] = $list;
		}else{
			$res['code'] = 1;
			$res['info'] = "获取责任部门列表失败";
		}

		echo json_encode($res);

	}

	/*
		各网格内设备故障统计表
	 */
	public function device_trouble_table()
	{

		$start_time = $this->input->post('start');
		$end_time  = $this->input->post('end');
		$departments = $this->input->post('departments');
		$start_time = $start_time." 00:00:00";
		$end_time = $end_time."23:59:59";
		$start_time = strtotime($start_time);
		$end_time = strtotime($end_time);
		$list = $this->db->select('grid_name,t_device.device_name,device_type_name,department_name')
				->from('t_device')
				->join('t_grid','t_grid.grid_id = t_device.grid_id','left')
				->join('t_device_type','t_device_type.device_type_id = t_device.device_type_id','left')
				->join('t_department','t_department.department_id = t_device_type.department_id','left')
				->join('t_device_report','t_device_report.device_id = t_device.device_id','left')
				->where('report_addtime between '.$start_time.' and '.$end_time)
				->where_in('t_device_type.department_id',$departments)
				->group_by('t_device.device_id')
				->get()
				->result_array();
		$list1 = $this->db->select('grid_name,count(t_device.device_id) as device_num')
				->from('t_device')
				->join('t_grid','t_grid.grid_id = t_device.grid_id')
				->group_by('t_device.grid_id')
				->get()
				->result_array();
		$list2 = $this->db->select('t_device.device_name,count(t_device_report.device_id) as report_num')
				->from('t_device_report')
				->join('t_device','t_device.device_id = t_device_report.device_id','left')
				->where('report_addtime between '.$start_time.' and '.$end_time)
				->group_by('t_device_report.device_id')
				->get()
				->result_array();
		$list3 = $this->db->select('t_device.device_name,count(t_device_task.repairtask_id) as repair_num')
				->from('t_device_task')
				->join('t_device_repairtask','t_device_repairtask.repairtask_id = t_device_task.repairtask_id','left')
				->join('t_device_report','t_device_report.report_id = t_device_repairtask.report_id','left')
				->join('t_device','t_device.device_id = t_device_report.device_id')
				->where('report_addtime between '.$start_time.' and '.$end_time)
				->group_by('t_device.device_name')
				->get()
				->result_array();
		foreach($list as $k => $v)
		{
			$list[$k]['device_num'] = 0;
			$list[$k]['report_num'] = 0;
			$list[$k]['repair_num'] = 0;
			foreach($list1 as $k1 => $v1)
			{
				if($v['grid_name'] == $v1['grid_name'])
				{
					$list[$k]['device_num'] = $v1['device_num'];
				}
			}
			foreach($list2 as $k2 => $v2)
			{
				if($v['device_name'] == $v2['device_name'])
				{
					$list[$k]['report_num'] = $v2['report_num'];
				}
			}
			foreach($list3 as $k3 => $v3)
			{
				if($v['device_name'] == $v3['device_name'])
				{
					$list[$k]['repair_num'] = $v3['repair_num'];
				}
			}
		}
		if($list)
		{
			$res['code'] = 0;
			$res['info'] = "获取成功";
			$res['data'] = $list;
		}else{
			$res['code'] = 1;
			$res['info'] = "获取失败,暂无数据";
		}

		echo json_encode($res);
		
	}

	/*
		设备类型列表
	 */
	public function device_type_list()
	{

		$list = $this->db->select('device_type_id as id,device_type_name as text')
				->from('t_device_type')
				->get()
				->result_array();
		if($list)
		{
			$res['code'] = 0;
			$res['info'] = "获取设备类型列表成功";
			$res['data'] = $list;
		}else{
			$res['code'] = 1;
			$res['info'] = "获取设备类型列表失败";
		}

		echo json_encode($res);

	}

	/*
		设备故障数统计图
	 */
	public function device_trouble_num_chart()
	{

		$data = $this->input->post();
		unset($data['device_type_names']);
		$device_type_names = $this->input->post('device_type_names');
		// $data['type'] = 3;
		// $data['year'] = 2017;
		// $data['month'] = array(8,9,10,11,12);
		// $device_type_names =array(1,2,3,4);
		if(!empty($data['type']))
		{
			$time = $this->check_time($data);
		}else{
			
			$time[0]['first'] = date('Y-m-01 00:00:00');
			$time[0]['last'] = date('Y-m-01 00:00:00',strtotime('+1 month'));
			
		}
		$list = $this->db->select('device_type_name')
				->from('t_device_type')
				->where_in('device_type_id',$device_type_names)
				->group_by('t_device_type.device_type_id')
				->get()
				->result_array();
		foreach($time as $k => $v)
		{
			$time['first'] = strtotime($v['first']);
			$time['last'] = strtotime($v['last']);
			$list1 = $this->db->select('t_device_type.device_type_name,count(report_id) as device_trouble_num')
					->from('t_device_type')
					->join('t_device_report','t_device_report.device_type_id = t_device_type.device_type_id','left')
					->where('report_addtime between '.$time['first'].' and '.$time['last'])
					->where_in('t_device_type.device_type_id',$device_type_names)
					->group_by('t_device_type.device_type_id')
					->get()
					->result_array();
			foreach($list as $k1 => $v1)
			{
				$arr[$k]['device_trouble_num'][$k1] = '0';
				foreach($list1 as $k2 => $v2)
				{
					if($v1['device_type_name'] == $v2['device_type_name'])
					{
						$arr[$k]['device_trouble_num'][$k1] = $v2['device_trouble_num'];
					}
				}
			}
		}
		// print_r($arr);die;
		foreach($list as $k => $v)
		{
			$result['chartxname'][] = $v['device_type_name'];
		}
		foreach($arr as $k => $v)
		{
			$result['chartxdata'][$k] = $v['device_trouble_num'];
		}
		// print_r($result);die;
		if($result)
		{
			$res['code'] = 0;
			$res['info'] = "获取成功";
			$res['data'] = $result;
		}else{
			$res['code'] = 1;
			$res['info'] = "获取失败,暂无数据";
		}
		// print_r($result);die;
		echo json_encode($res);

	}

	/*
		设备故障数统计表
	 */
	public function device_trouble_num_table()
	{

		$start_time = $this->input->post('start');
		$end_time = $this->input->post('end');
		$departments = $this->input->post('departments');
		if($departments == '0')
		{
			$departments = NULL;
		}
		$start_time = $start_time." 00:00:00";
		$end_time = $end_time."23:59:59";
		$start_time = strtotime($start_time);
		$end_time = strtotime($end_time);
		$list = $this->db->select('grid_name,t_device.device_name,device_type_name,department_name')
				->from('t_device')
				->join('t_grid','t_grid.grid_id = t_device.grid_id','left')
				->join('t_device_type','t_device_type.device_type_id = t_device.device_type_id','left')
				->join('t_department','t_department.department_id = t_device_type.department_id','left')
				->join('t_device_report','t_device_report.device_id = t_device.device_id','left')
				->where('report_addtime between '.$start_time.' and '.$end_time)
				->where_in('t_device_type.department_id',$departments)
				->group_by('t_device.device_id')
				->get()
				->result_array();
		$list1 = $this->db->select('t_device.device_name,count(t_device_report.device_id) as report_num')
				->from('t_device_report')
				->join('t_device','t_device.device_id = t_device_report.device_id','left')
				->where('report_addtime between '.$start_time.' and '.$end_time)
				->group_by('t_device_report.device_id')
				->get()
				->result_array();
		$list2 = $this->db->select('t_device.device_name,count(t_device_task.repairtask_id) as repair_num')
				->from('t_device_task')
				->join('t_device_repairtask','t_device_repairtask.repairtask_id = t_device_task.repairtask_id','left')
				->join('t_device_report','t_device_report.report_id = t_device_repairtask.report_id','left')
				->join('t_device','t_device.device_id = t_device_report.device_id')
				->where('report_addtime between '.$start_time.' and '.$end_time)
				->group_by('t_device.device_name')
				->get()
				->result_array();
		foreach($list as $k => $v)
		{
			$list[$k]['report_num'] = 0;
			$list[$k]['repair_num'] = 0;
			foreach($list1 as $k1 => $v1)
			{
				if($v['device_name'] == $v1['device_name'])
				{
					$list[$k]['report_num'] = $v1['report_num'];
				}
			}
			foreach($list2 as $k2 => $v2)
			{
				if($v['device_name'] == $v2['device_name'])
				{
					$list[$k]['repair_num'] = $v2['repair_num'];
				}
			}
		}
		if($list)
		{
			$res['code'] = 0;
			$res['info'] = "获取成功";
			$res['data'] = $list;
		}else{
			$res['code'] = 1;
			$res['info'] = "获取失败,暂无数据";
		}
		// print_r($list);die;
		echo json_encode($res);

	}

	/*
		设备各维修岗位工作量统计图
	 */
	public function device_repair_chart()
	{

		$data = $this->input->post();
		if(isset($data['department_id']))
		{
			unset($data['department_id']);
		}
		$department_id = $this->input->post('department_id');
		if(!empty($data['type']))
		{
			$time = $this->check_time($data);
		}else{
			
			$time['first'] = date('Y-m-01 00:00:00');
			$time['last'] = date('Y-m-01 00:00:00',strtotime('+1 month'));
		}
		$time['first'] = strtotime($time['first']);
		$time['last'] = strtotime($time['last']);
		$list = $this->db->select('t_device.wx_post_name as name,count(t_device_task.task_id) as value')
				->from('t_device_task')
				->join('t_device_repairtask','t_device_repairtask.repairtask_id = t_device_task.repairtask_id','left')
				->join('t_device_report','t_device_report.report_id = t_device_repairtask.report_id','left')
				->join('t_device','t_device.device_id = t_device_report.device_id','left')
				// ->join('t_post','t_post.post_id = t_device.wx_post_id','left')
				->join('t_device_type','t_device_type.device_type_id = t_device.device_type_id','left')
				->where('t_device_type.department_id',$department_id)
				->or_where('t_device_task.task_addtime between '.$time['first'].' and '.$time['last'])
				->group_by('t_device.wx_post_id')	
				->get()
				->result_array();
		$list1 = $this->db->select('wx_post_name as name')
				->from('t_device')
				->group_by('wx_post_id')
				->get()
				->result_array();
		// print_r($list);die;
		foreach($list1 as $k1 => $v1)
		{
			$result['chartxname'][$k1] = $v1['name'];
			$result['chartxdata'][$k1]['name'] = $v1['name'];
			$result['chartxdata'][$k1]['value'] = '0';
			foreach($list as $k => $v)
			{
				
				if($v['name'] == $v1['name'])
				{
					$result['chartxdata'][$k1]['value'] = $v['value'];
				}
			}
		}
		// print_r($result);die;
		if($result)
		{
			$res['code'] = 0;
			$res['info'] = "获取成功";
			$res['data'] = $result;
		}else{
			$res['code'] =1;
			$res['info'] = "获取失败";
		}

		echo json_encode($res);

	}

	/*
		设备各维修岗位工作量统计表
	 */
	public function device_repair_table()
	{

		$start_time = $this->input->post('start');
		$end_time = $this->input->post('end');
		$departments = $this->input->post('departments');
		$start_time = $start_time." 00:00:00";
		$end_time = $end_time."23:59:59";
		$start_time = strtotime($start_time);
		$end_time = strtotime($end_time);
		$list = $this->db->select('wx_post_name,department_name')
				->from('t_device')
				->join('t_post','t_post.post_id = t_device.wx_post_id','left')
				->join('t_department','t_department.department_id = t_post.department_id','left')
				->where_in('t_department.department_id',$departments)
				->group_by('wx_post_id')
				->get()
				->result_array();
		$list1 = $this->db->select('wx_post_name,count(report_id) as report_num')
				->from('t_device_report')
				->join('t_device','t_device.device_id = t_device_report.device_id','left')
				->where('t_device_report.report_addtime between '.$start_time.' and '.$end_time)
				->group_by('wx_post_id')
				->get()
				->result_array();
		$list2 = $this->db->select('t_device.wx_post_name,count(t_device_task.task_id) as repair_num')
				->from('t_device_task')
				->join('t_device_repairtask','t_device_repairtask.repairtask_id = t_device_task.repairtask_id','left')
				->join('t_device_report','t_device_report.report_id = t_device_repairtask.report_id','left')
				->join('t_device','t_device.device_id = t_device_report.device_id','left')
				->or_where('t_device_task.task_addtime between '.$start_time.' and '.$end_time)
				->group_by('t_device.wx_post_id')	
				->get()
				->result_array();
		foreach($list as $k => $v)
		{
			$list[$k]['report_num'] = 0;
			$list[$k]['repair_num'] = 0;
			$list[$k]['xj_num'] = 0;
			foreach($list1 as $k1 => $v1)
			{
				if($v['wx_post_name'] == $v1['wx_post_name'])
				{
					$list[$k]['report_num'] = $v1['report_num'];
				}
			}
			foreach($list2 as $k2 => $v2)
			{
				if($v['wx_post_name'] == $v2['wx_post_name'])
				{
					$list[$k]['repair_num'] = $v2['repair_num'];
				}
			}
		}
		if($list)
		{
			$res['code'] = 0;
			$res['info'] = "获取成功";
			$res['data'] = $list;
		}else{
			$res['code'] = 0;
			$res['info'] = "获取失败";
		}

		echo json_encode($res);

	}

	/*
		接发车岗位任务完成情况（柱状图）
	 */
	public function train_post_chart()
	{



	}

	/*
		设备巡检任务完成情况（柱状图）
	 */
	public function device_xun_chart()
	{



	}

	/*
		各作业网格任务完成情况（柱状图）
	 */
	public function grid_work_chart()
	{



	}

	/*
		车站干部网格巡视统计表（表）
	 */
	public function leader_grid_table()
	{



	}

	/*
		设备部门维修人员合格率（表）
	 */
	public function repair_pass_table()
	{

		$start_time = $this->input->post('start');
		$end_time = $this->input->post('end');
		$departments = $this->input->post('departments');
		$posts = $this->input->post('posts');
		$start_time = $start_time." 00:00:00";
		$end_time = $end_time."23:59:59";
		$start_time = strtotime($start_time);
		$end_time = strtotime($end_time);
		$list = $this->db->select('t_device_task.user_id,user_name,department_name')
				->from('t_device_task')
				->join('t_user','t_user.user_id = t_device_task.user_id','left')
				->join('t_department','t_department.department_id = t_user.department_id','left')
				// ->join('t_device_repairtask','t_device_repairtask.repairtask_id = t_device_task.repairtask_id','left')
				// ->join('t_device_report','t_device_report.report_id = t_device_repairtask.report_id','left')
				// ->join('t_device','t_device.device_id = t_device_report.device_id','left')
				// ->where_in('wx_post_id',$posts)
				->where('the_task_type',2)
				->where_in('t_user.department_id',$departments)
				->group_by('t_device_task.user_id')
				->get()
				->result_array();
		$list1 = $this->db->select('post_name,post_user')
				->from('t_post')
				->where('post_type_id',1)
				->where_in('post_id',$posts)
				->get()
				->result_array();
		$list2 = $this->db->select('user_id,count(task_id) as pass_num')
				->from('t_device_task')
				->where('task_donetime between '.$start_time.' and '.$end_time)
				->where(['task_result' => 1,'the_task_type' =>2])
				->group_by('user_id')
				->get()
				->result_array();
		$list3 = $this->db->select('user_id,count(task_id) as false_num')
				->from('t_device_task')
				->where('task_donetime between '.$start_time.' and '.$end_time)
				->where(['task_result' => 2,'the_task_type' =>2])
				->group_by('user_id')
				->get()
				->result_array();
		foreach($list as $k => $v)
		{
			foreach($list1 as $k1 => $v1)
			{
				$v1['post_user'] = explode(',',$v1['post_user']);
				if(in_array($v['user_id'],$v1['post_user']))
				{
					$list[$k]['post_name'] = $v1['post_name'];
				}
			}
			foreach($list2 as $k2 => $v2)
			{
				if($v['user_id'] == $v2['user_id'])
				{
					$list[$k]['pass_num'] = $v2['pass_num'];
				}
			}
			foreach($list3 as $k3 => $v3)
			{
				if($v['user_id'] == $v3['user_id'])
				{
					$list[$k]['false_num'] = $v3['false_num'];
				}
			}
			$list[$k]['all_num'] = $list[$k]['pass_num'] + $list[$k]['false_num'];
			$list[$k]['pass_percent'] = round($list[$k]['pass_num'] / $list[$k]['all_num'] * 100,2).'%';
		}

		if($list)
		{
			$res['code'] = 0;
			$res['info'] = "获取成功";
			$res['data'] = $list;
		}else{
			$res['code'] = 1;
			$res['info'] = "获取失败";
		}

		echo json_encode($res);

	}

	/*
		设备部门维修时间统计表（表）
	 */
	public function repair_time_table()
	{

		$start_time = $this->input->post('start');
		$end_time = $this->input->post('end');
		$departments = $this->input->post('departments');
		$start_time = $start_time." 00:00:00";
		$end_time = $end_time."23:59:59";
		$start_time = strtotime($start_time);
		$end_time = strtotime($end_time);
		/*
			根据维修任务数量和验收任务的数量判断使用和还是取最大值
		 */
		$list1 = $this->db->select('t_device.device_name,t_device_report.report_id,department_name,report_addtime,the_task_type,task_donetime,t_device_task.repairtask_id,report_addtime as report_time,sum(task_donetime) as repair_time,max(task_donetime) as max_time,count(task_donetime) as count')
				->from('t_device')
				->join('t_device_type','t_device_type.device_type_id = t_device.device_type_id','left')
				->join('t_department','t_department.department_id = t_device_type.department_id','left')
				->join('t_device_report','t_device_report.device_id = t_device.device_id')
				->join('t_device_repairtask','t_device_repairtask.report_id = t_device_report.report_id')
				// ->join('t_device_inspecttask','t_device_inspecttask.report_id = t_device_report.report_id')
				->join('t_device_task','t_device_task.repairtask_id = t_device_repairtask.repairtask_id')
				->where('task_donetime between '.$start_time.' and '.$end_time)
				->where('report_status',4)
				->where_in('department_id',$departments)
				->group_by('report_id')
				->get()
				->result_array();
		$list2 = $this->db->select('t_device.device_name,t_device_report.report_id,department_name,the_task_type,task_donetime,t_device_inspecttask.inspecttask_id,sum(task_donetime) as inspect_time,max(task_donetime) as max_time,count(task_donetime) as count')
				->from('t_device')
				->join('t_device_type','t_device_type.device_type_id = t_device.device_type_id','left')
				->join('t_department','t_department.department_id = t_device_type.department_id','left')
				->join('t_device_report','t_device_report.device_id = t_device.device_id')
				->join('t_device_inspecttask','t_device_inspecttask.report_id = t_device_report.report_id')
				->join('t_device_task','t_device_task.inspecttask_id = t_device_inspecttask.inspecttask_id')
				->where('task_donetime between '.$start_time.' and '.$end_time)
				->where('report_status',4)
				->where_in('department_id',$departments)
				->group_by('report_id')
				->get()
				->result_array();
		foreach($list1 as $k1 => $v1)
		{
			$list[$k1]['device_name'] = $v1['device_name'];
			$list[$k1]['department_name'] = $v1['department_name'];
			
			foreach($list2 as $k2 => $v2)
			{
				if($v1['report_id'] == $v2['report_id'])
				{
					if($v1['count'] > $v2['count'])
					{
						$list[$k1]['repair_time'] = $v1['max_time'] - $v1['report_time'];
						$list[$k1]['inspect_time'] = $list2[$k2]['inspect_time'] - $list1[$k1]['max_time'];
					}else{
						$list[$k1]['repair_time'] = $v1['repair_time'] - $v1['report_time'] - $v2['inspect_time'] + $v2['max_time'];
						$list[$k1]['inspect_time'] = $v2['inspect_time'] - $v1['repair_time'];
					}
					
				}
			}
			$list[$k1]['all_time'] = $list[$k1]['repair_time'] + $list[$k1]['inspect_time'];
		}
		foreach($list as $k => $v)
		{
			$list[$k]['repair_time'] = $this->timediff($v['repair_time']);
			$list[$k]['inspect_time'] = $this->timediff($v['inspect_time']);
			$list[$k]['all_time'] = $this->timediff($v['all_time']);
		}
		
		if($list)
		{
			$res['code'] = 0;
			$res['info'] = "获取成功";
			$res['list'] = $list;
		}else{
			$res['code'] = 1;
			$res['info'] = "获取失败";
		}

		echo json_encode($res);

	}

	/*
		时间戳相减结果转换得到相差时间
	 */
	public function timediff($timediff)
	{
		//计算天数
		$days = intval($timediff/86400);
		//计算小时数
		$remain = $timediff%86400;
		$hours = intval($remain/3600);
		//计算分钟数
		$remain = $remain%3600;
		$mins = intval($remain/60);
		//计算秒数
		$secs = $remain%60;
		if($days == 0)
		{
			if($hours == 0)
			{
				$res = $mins.'分'.$secs.'秒';
			}else{
				$res = $hours.'小时'.$mins.'分'.$secs.'秒';
			}
		}else{
			$res = $days.'天'.$hours.'小时'.$mins.'分'.$secs.'秒';
		}
		return $res;
	}

	/*
		人员作业量信息对比（柱状图）
	 */
	public function user_work_chart()
	{



	}

	/*
		人员作业量信息对比（表）
	 */
	public function user_work_table()
	{



	}
	
	/*
		部门作业量信息对比（柱状图）
	 */
	public function department_work_chart()
	{



	}

	/*
		部门作业量信息对比（表）
	 */
	public function department_work_table()
	{



	}

	/*
		量化考核干部网格巡视完成情况（柱状图）
	 */
	public function leader_grid_pass_chart()
	{



	}

	/*
		量化考核干部网格巡视完成情况（表）
	 */
	public function leader_grid_pass_table()
	{



	}

	/*
		量化考核干部网格巡视完成情况详情（表）
	 */
	public function leader_grid_pass_info()
	{



	}
	//设备维修所用时间
	function get_time1($begin_time,$end_time,$a)
	{
		if($begin_time < $end_time){
		             $starttime = $begin_time;
		             $endtime = $end_time;
		}else{
		             $starttime = $end_time;
		             $endtime = $begin_time;
		}
      		//计算天数
    		$timediff = $endtime-$starttime;
      		$days = intval($timediff/86400);
      		//计算小时数
      		$remain = $timediff%86400;
      		$hours = intval($remain/3600);
      		//计算分钟数
      		$remain = $remain%3600;
      		$mins = intval($remain/60);
      		//计算秒数
      		$secs = $remain%60;
     		if($secs>0)
        		$mins+=1;
   	// 	if($hours>12 || $days>0){
    //     			$res = "<font color='red'>".$days."天".$hours."时".$mins."分"."</font>";
    // 		}else{
    //    			$res = "<font color='green'>".$days."天".$hours."时".$mins."分"."</font>";
  		// }
      		if($a==1){
        			$res = $days."天".$hours."时".$mins."分";
      		}
      		// $res = array("day" => $days,"hour" => $hours,"min" => $mins,"sec" => $secs);
      		return $res;
	}
	//报修记录导出
    	public function recordexport(){
    		$status = $this->input->get_post("status");//状态
	             $dept = $this->input->get_post("dept");//部门
	             $starttime = $this->input->get_post("start_time");//ajax
	             $endtime = $this->input->get_post("end_time");//ajax
	             $start_time = strtotime($starttime);
	             $end_time = strtotime(date('Y-m-d 23:59:59', strtotime($endtime)));
	             $where = " where 1=1";
	             // $where=' where r.report_addtime>='.$start_time.' AND r.report_addtime<='.$end_time;
	             if(!empty($status)){
	             	$where.=" AND r.report_status=".$status;
	             }
	             if(!empty($dept)){
	             	$where.=" AND t.department_id=".$dept;
	             }
                     	$data   = $this->M_device->get_Areadata($where,$limit='',$type=2);
        		set_include_path(get_include_path() . PATH_SEPARATOR . APPPATH . 'libraries');
        		ini_set('include_path', ini_get('include_path').PATH_SEPARATOR.APPPATH.'libraries/');
        		require_once 'PHPExcel.php';
        		include_once APPPATH.'libraries/PHPExcel/IOFactory.php';
        		$objPHPExcel = new PHPExcel();
        		$account_name =date("Y").date("m").date("d").date("H").date("i").date("s");
        		$objPHPExcel->getProperties()->setCreator("ids5")
            			->setLastModifiedBy("ids5")
            			->setTitle($account_name."维修时间导出信息")
            			->setSubject($account_name."维修时间导出信息")
            			->setDescription($account_name."维修时间导出信息")
            			->setKeywords("office 2007 openxml php")
            			->setCategory($account_name."维修时间导出信息");
        		//名称
        		$excel_arr = array('A'=>'序号',
		            'B'=>'设备名称',
		            'C'=>'设备类型',
		            'D'=>'设备位置',
		            'E'=>'所属网格',
		            'F'=>'所属部门',
		            'G'=>'报修时间',
		            'H'=>'设备状态',
		            'H'=>'维修次数',);
	        	foreach ($excel_arr as $key => $val){
	            		$objPHPExcel->setActiveSheetIndex()->setCellValue($key.'1',$val);
	        	}

        		//宽度
        		$objPHPExcel->getActiveSheet()->setTitle('维修设备信导出');
        		$excel_len = array('A'=>'30','B'=>'15','C'=>'30','D'=>'20','E'=>'15','F'=>'20','G'=>'25','H'=>'25','I'=>'25','J'=>'15','K'=>'20');
        		foreach ($excel_len as $keys =>$vals){
            			$objPHPExcel->getActiveSheet()->getColumnDimension($keys)->setWidth($vals);
       		}
        		$num = 1;
        		$status = array('1'=>'报修','2'=>'维修','3'=>'验收','4'=>'正常');
          		foreach($data as &$v){
                            	$v['device_name'] = isset($v['device_name'])?$v['device_name']:""; //网格名称
                            	$v['device_type_name'] = isset($v['device_type_name'])?$v['device_type_name']:""; //网格名称
                            	$v['area_name'] = isset($v['area_name'])?$v['area_name']:"";  //设备名称
                            	$v['grid_name'] = isset($v['grid_name'])?$v['grid_name']:"";  //设备名称
                           
                            	$v['department_name'] = isset($v['department_name'])?$v['department_name']:"";  //
                            	$v['report_addtime'] = isset($v['report_addtime'])?date('Y-m-d H:i:s',$v['report_addtime']):"";  //
	                          $v['report_status'] = $status[$v['report_status']];  //设备状态
                            	$v['num'] = isset($v['num'])?$v['num']:"";  //巡检
                            	$v['ys'] = $this->get_time1($v['task_time'],$v['task_donetime'],$a=1);
	            		$num++;
	            		$objPHPExcel->setActiveSheetIndex()->setCellValue('A'.$num,$v['report_id'])
	                		->setCellValue('B'.$num,$v['device_name'])
	                		->setCellValue('C'.$num,$v['device_type_name'])
	                		->setCellValue('D'.$num,$v['area_name'])
	                		->setCellValue('E'.$num,$v['grid_name'])
	                		->setCellValue('F'.$num,$v['department_name'])
	                		->setCellValue('G'.$num,$v['report_addtime'])
	                		->setCellValue('H'.$num,$v['report_status'])
	                		->setCellValue('I'.$num,$v['num'])
	                		->setCellValue('J'.$num,$v['ys']);
        		}

        		$FileNames = mb_convert_encoding($account_name,'gb2312','UTF-8');
        		$FileNames = $FileNames."_export_file";
        		header('Content-Type: application/vnd.ms-excel');
        		header('Content-Disposition: attachment;filename="'.$FileNames.'.xls"');
        		header('Cache-Control: max-age=0');
        		$objWriter = IOFactory::createWriter($objPHPExcel, 'Excel5');
        		ob_end_clean();//清空（擦除）缓冲区并关闭输出缓冲
        		$objWriter->save('php://output');
       		exit;
    	}


}